/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var seednia = seednia || {};

var TASK_STATUS_INCOMPLETE = 1;
var TASK_STATUS_COMPLETED = 4;
var SYS_STATUS_ARCHIVED = 1;

seednia.Actionable = Backbone.Model.extend({
	idAttribute: "sid",
	//url: "http://localhost/seednia-uiphp-nb/rsactionable.php/actionable",
	urlRoot: "http://localhost/seednia-uiphp-nb/rsactionable.php/actionable",
	
	defaults: {
		// Ensure that each photo created has an `src`.
		projectSid: -2,
		projectName: ""
	},
	
	toggleComplete: function() {
		if (this.get('status') != TASK_STATUS_COMPLETED)
			this.setStatus(TASK_STATUS_COMPLETED);
		else
			this.setStatus(TASK_STATUS_INCOMPLETE);
	},

	isCompleted: function() {
		return this.get('status') >= TASK_STATUS_COMPLETED;
	},
	
	isArchived: function() {
		return this.get('sysStatus') == SYS_STATUS_ARCHIVED;
	},
	
	// 1=assigned,  4=complete
	setStatus: function(val) {
		this.set({status: val});
	},
	
	// -1=deleted, 0=active, 1=archived
	setSysStatus: function(val) {
		this.set({sysStatus: val});
	}
});

seednia.ActionableCollection = Backbone.Collection.extend({

	// Reference to this collection's model.
	model: seednia.Actionable,
	initialize : function(models, criteria) {
		this.domainId = criteria.domainId;
		this.projectSid = criteria.projectSid;
		this.creatorSid = criteria.creatorSid;
	},
	url : function() {
		if (this.userSid != null && this.userSid  > 0)
			return "http://localhost/seednia-uiphp-nb/rsactionable.php/user/actionables/" + this.userSid;
		else 
			return "http://localhost/seednia-uiphp-nb/rsactionable.php/project/actionables/" + this.projectSid;
	},
	
	// Filter down the list of all actionable items that are was completed
	completed: function() {
		return this.filter(function( actionable ) {
			return (actionable.get('status') >= TASK_STATUS_COMPLETED);
		});
	},
	// Filter down the list to only todo items that are still not finished.
	remaining: function() {
		return this.without.apply( this, this.completed() );
	},
	
	// Todos are sorted by their original insertion order.
	comparator: function( actionable ) {
		return actionable.get('sid');
	}
});


seednia.ActionableView = Backbone.View.extend({

	//... is a list tag.
	tagName:  "li",
	className:  "actionable-entry",

	// Pass the contents of the photo template through a templating
	// function, cache it for a single photo
	template: _.template($('#actionable-template').html()),

	// The DOM events specific to an item.
	events: {
		"click .toggle"   : "toggleCompleted",
		"dblclick .view"  : "edit",
		"click a.delete"  : "deleteActionable",
		"keypress .edit"  : "updateOnEnter",
		"blur .edit"      : "close"
	},

	// The PhotoView listens for changes to its model, re-rendering. Since there's
	// a one-to-one correspondence between a **Photo** and a **PhotoView** in this
	// app, we set a direct reference on the model for convenience.
	initialize: function() {
		//_.bindAll(this, 'render');
		this.model.on('reset', this.render, this);
		this.model.on('change', this.render, this);
		this.model.on('destroy', this.remove, this);
		//this.model.bind('destroy', this.remove, this); // bind is for backward compatibility
	},

	// Re-render the photo entry
	render: function() {
		this.$el.html(this.template(this.model.toJSON()));
		// add 'completed' class to the element (for strikeout decoration)
		this.$el.toggleClass( 'completed', this.model.isCompleted() );
		this.$el.toggleClass( 'archived', this.model.isArchived() );
		this.input = this.$('.edit');
		return this;
	},
	
	// Toggle the "completed" state of the model.
	toggleCompleted: function() {
		this.model.toggleComplete();
		this.model.save();
	},
	
	edit: function() {
		this.$el.addClass("editing");
		this.input.focus();
	},
	
	// Close the "editing" mode, saving changes to the actionable.
	close: function() {
		var value = this.input.val().trim();
		if (!value) {
			this.clear();
		} else {
			this.model.save({
				name: value
			});
		}
		this.$el.removeClass("editing");
	},

	// If you hit `enter`, we're through editing the item.
	updateOnEnter: function(e) {
		if ( e.which === 13 ) this.close();
	},
	
	deleteActionable: function() {
		this.model.destroy();
	}

});


seednia.ActionableComponentView = Backbone.View.extend({
	// Instead of generating a new element, bind to the existing skeleton of
	// the App already present in the HTML.
	el: $("#actionable-component"),
	
	statsTemplate: _.template( $('#stats-template').html() ),

	// Delegated events for creating new items, and clearing completed ones.
	events: {
		"keypress #new-actionable":  "createOnEnter",
		"click #clear-completed": "hideCompleted"
	},

	// At initialization we bind to the relevant events on the 'Actionables'
	// collection, when items are added or changed. Kick things off by
	// loading any preexisting actionables that might be saved in REST.
	initialize: function() {
		this.input = this.$("#new-actionable");

		this.collection.on('add', this.addOne, this);
		this.collection.on('reset', this.addAll, this);
		this.collection.on('all', this.render, this);
		this.collection.on('remove', this.unrender, this);

		this.$main = $('#actionable-component-main');
		this.$footer = this.$('#actionable-component-footer');
		
		this.projectSid = -2; // projectSid is optional
		if(this.options.domainId) {
			this.domainId = this.options.domainId;
		}
		if(this.options.projectSid) {
			this.projectSid = this.options.projectSid;
		}
		if(this.options.creatorSid) {
			this.creatorSid = this.options.creatorSid;
		}

		this.collection.fetch();
	},

	// Re-rendering the Component does nothing (for now).
	render: function() {
		var completed = this.collection.completed().length;
		var remaining = this.collection.remaining().length;
		
		if ( this.collection.length ) {
			this.$main.show();
			this.$footer.show();

			this.$footer.html(this.statsTemplate({
				completed: completed,
				remaining: remaining
			}));

		} else {
			this.$main.hide();
			this.$footer.hide();
		}
	},

	// Add a single actionable item to the list by creating a view for it, and
	// appending its element to the `<ul>`.
	addOne: function(actionable) {
		var view = new seednia.ActionableView({
			model: actionable
		});
		this.$("#actionable-list").append(view.render().el);
	},

	// Add all items in the actionable collection at once.
	addAll: function() {
		this.collection.each(this.addOne);
	},
	
	newAttributes: function() {
		return {
			domainId: this.collection.domainId,
			creatorSid: this.collection.creatorSid,
			projectSid: this.collection.projectSid,
			name: this.input.val().trim()
		}
	},

	// If you hit return in the main input field, create new Actionable model,
	// persisting it to *localStorage*.
	createOnEnter: function(e) {
		if ( e.which !== 13 || !this.input.val().trim() ) {
			return;
		}

		var newActionable = this.collection.create(this.newAttributes());
		//newActionable.save(); => this is not required as the collection does it auto.
		this.input.val('');
	},
	
	// Unrender removed (deleted/archived) actionables
	unrender: function() {
		// hide completed
		this.$("#actionable-list .completed").hide();
	},

	// Hide all done actionable items updating the status to 5.
	hideCompleted: function() {
		theCollection = this.collection;
		_.each(this.collection.completed(), function(actionable){
			actionable.setSysStatus(SYS_STATUS_ARCHIVED+1);
			actionable.save();
			theCollection.remove(actionable);
		});
		//var completedItems = this.collection.completed();
		//this.collection.remove(completedItems);
		return false;
	}
})
//var _actionableListView = new seednia.actionableView({ el: $("#actionable_contsiner") });
